<?php

namespace App\Models;

use App\Helpers\ConfigTrait;
use App\Models\Scope\OnSaleScope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;

class OrderItem extends Model
{
    use ConfigTrait;

    protected $fillable = ['amount', 'price', 'rating', 'review', 'reviewed_at', 'product_sku_name', 'product_title', 'product_image'];

    protected $dates = ['reviewed_at'];

    public $timestamps = false;

    // 关联产品
    public function product()
    {
        return $this->belongsTo(Product::class);
    }

    // 关联规格
    public function productSku()
    {
        return $this->belongsTo(ProductSku::class);
    }

    // 关联order
    public function order()
    {
        return $this->belongsTo(Order::class);
    }

    // 关联 订单 优惠邮费明细
    public function adj()
    {
        return $this->hasOne(Adjustments::class, 'order_item_id', 'id');
    }

    // 关联售后
    public function afterSale()
    {
        return $this->hasOne(AfterSale::class, 'order_item_id', 'id');
    }

    // 获取售后状态
    public function getAfterSaleStatusAttribute() {
        return $this->afterSale()->value('status') ?? 0;
    }

    // 获取售后的时间是否有7天
    public function getAfterSaleIsTimeAttribute()
    {
        $data = $this->getConfigValue('shipped_config');
        $time = Carbon::parse($this->afterSale()->value('created_at'));
        $service = $this->product()->withoutGlobalScope(OnSaleScope::class)->value('server_id');
        if (now()->diffInDays($time) > $data['completed'] || empty($service)) {
            return false;
        }
        return true;
    }

    // 补全图片全路径
    public function getProductImageAttribute($value)
    {
        if (empty($value)) {
            return $this->attributes['image'] = $this->product()->value('image');
        }
        return $this->attributes['image'] = config('upload.ossUrl').$value;
    }
}
